package cc.eddic.pratice.programmingparadigms.nginxlog.impl;

import cc.eddic.pratice.programmingparadigms.nginxlog.LogItem;
import cc.eddic.pratice.programmingparadigms.nginxlog.LogItemParser;
import cc.eddic.pratice.programmingparadigms.nginxlog.NginxLogItem;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;

public class LogItemParserLhImpl implements LogItemParser {

    @Override
    public Optional<LogItem> parse(NginxLogItem nginxLogItem) {
        String s = nginxLogItem.getRequest();
        String[] request = s.split(" ");
        Map<String, String> query = new HashMap<>();
        if (request.length < 3) return Optional.empty();
        String path;
        if (!request[1].contains("?")) path = request[1];
        else {
            path = request[1].substring(0, request[1].indexOf("?"));
        }
//TODO 调整时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
        LocalDateTime localtime=LocalDateTime.parse(nginxLogItem.getTime(),formatter);
        return Optional.of(new LogItem(
                nginxLogItem.getIp(),
                localtime,
                request[0],
                path,
                query,
                request[2],
                Integer.parseInt(nginxLogItem.getStatus())
                , Long.parseLong(nginxLogItem.getBytes()),
                nginxLogItem.getReferer(),
                nginxLogItem.getUserAgent()
        ));
    }
}
